package com.anime.fragment;

import android.content.Intent;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;


import com.anime.activity.AnimePlayActivity;
import com.anime.activity.SearchAnimeActivity;
import com.anime.adapter.AnimeLrytAdapter;
import com.anime.adapter.AnimeTypeAdapter;

import com.anime.adapter.AnimeYHAdapter;
import com.anime.model.ViewModelSwitch;
import com.animes.R;
import com.animes.databinding.AnimeFragmentBinding;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import base.QFragment;
import base.QLoading;
import constant.AppConstants;
import http.Api;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import model.AnimeLRYSearchModel;
import model.AnimeYHSearchModel;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class AnimeFragment extends QFragment<AnimeFragmentBinding> {

    private AnimeTypeAdapter animeTypeAdapter;
    private ArrayList<String> typeList = new ArrayList<>();

    private String typeName = "电影";
    private int pageLRY = 1;
    private int pageYH = 1;
    private int pageSize = 10;

    private ArrayList<AnimeLRYSearchModel.DataBean> lryList = new ArrayList<>();
    private ArrayList<AnimeYHSearchModel.DataBean.ListBean> yhList = new ArrayList<>();
    private AnimeLrytAdapter animeLrytAdapter;
    private AnimeYHAdapter animeYHAdapter;


    private int networkIndex = 0;
    private int total;

    private HashMap map = new HashMap<Integer, String>();
    private Disposable disposable;

    private Call<AnimeLRYSearchModel> callLRY;
    private Call<AnimeYHSearchModel> callYH;
    private QLoading qLoading;
    private ViewModelSwitch viewModel;
    private boolean isOne;
    private boolean isDestroy;


    @Override
    public int getLayoutRes() {
        return R.layout.anime_fragment;
    }

    @Override
    public void initView() {

    }

    @Override
    public void initData() {

        viewModel = new ViewModelProvider(this).get(ViewModelSwitch.class);


        typeList.clear();
        typeList.add("电影");
        typeList.add("动漫");
        typeList.add("综艺");
        typeList.add("悬疑");
        typeList.add("港剧");

        GridLayoutManager layoutManager = new GridLayoutManager(getActivity(), 5, GridLayoutManager.VERTICAL, false);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        binding.rvType.setLayoutManager(layoutManager);
        animeTypeAdapter = new AnimeTypeAdapter(R.layout.anime_type_item, typeList);
        binding.rvType.setAdapter(animeTypeAdapter);


        // 设置刷新头部和尾部为经典样式
        binding.swipeLry.setRefreshHeader(new ClassicsHeader(getContext()));
        binding.swipeLry.setRefreshFooter(new ClassicsFooter(getContext()));


        binding.swipeYh.setRefreshHeader(new ClassicsHeader(getContext()));
        binding.swipeYh.setRefreshFooter(new ClassicsFooter(getContext()));

        GridLayoutManager lryLayoutManager = new GridLayoutManager(getActivity(), 2, GridLayoutManager.VERTICAL, false);
        lryLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        binding.rvLry.setLayoutManager(lryLayoutManager);
        animeLrytAdapter = new AnimeLrytAdapter(R.layout.anime_content_item, null);
        binding.rvLry.setAdapter(animeLrytAdapter);


        GridLayoutManager yhayoutManager = new GridLayoutManager(getActivity(), 2, GridLayoutManager.VERTICAL, false);
        yhayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        binding.rvYh.setLayoutManager(yhayoutManager);
        animeYHAdapter = new AnimeYHAdapter(R.layout.anime_content_item, null);
        binding.rvYh.setAdapter(animeYHAdapter);

        // 设置刷新头部和尾部为经典样式
        binding.swipeLry.setRefreshHeader(new ClassicsHeader(getContext()));
        binding.swipeLry.setRefreshFooter(new ClassicsFooter(getContext()));


    }

    @Override
    public void initListener() {


        animeTypeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                String item = (String) adapter.getData().get(position);
                pageLRY = 1;
                pageYH = 1;
                animeTypeAdapter.setIndex(position);
                animeTypeAdapter.notifyDataSetChanged();
                typeName = item;
                yhList.clear();
                lryList.clear();
                networkMessage();


            }

        });

        binding.swipeLry.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                //下拉刷新
                LogUtils.d("下拉刷新");
                pageLRY = pageLRY + 1;
                networkMessage();
                refreshLayout.finishLoadMore();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                //上拉
                LogUtils.d("上拉刷新");
//                pageNo = 1;
                networkMessage();
                refreshLayout.finishRefresh();
            }
        });

        binding.swipeYh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                //下拉刷新
                LogUtils.d("下拉刷新");

                if (pageYH * 20 < total) {
                    LogUtils.d("下拉刷新B");
                    pageYH = pageYH + 1;
                    getYHSearch(typeName);
                    LogUtils.d("我做了网络请求A");
                } else {
                    binding.swipeYh.finishLoadMoreWithNoMoreData();
                    LogUtils.d("下拉刷新CC");
                }
//                refreshLayout.finishLoadMore();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                //上拉
                LogUtils.d("上拉刷新");
//                pageNo = 1;
                networkMessage();
                refreshLayout.finishRefresh();
            }
        });


        animeLrytAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                AnimeLRYSearchModel.DataBean item = (AnimeLRYSearchModel.DataBean) adapter.getData().get(position);
                //videoId
                String videoId = item.getVideoId();
                Intent intent = new Intent(getActivity(), AnimePlayActivity.class);
                intent.putExtra("videoId", videoId);
                intent.putExtra("type", 1);
                intent.putExtra("pic", item.getCover());
                intent.putExtra("titleName", item.getTitle());
                startActivity(intent);

            }
        });


        animeYHAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                AnimeYHSearchModel.DataBean.ListBean item = (AnimeYHSearchModel.DataBean.ListBean) adapter.getData().get(position);
                Intent intent = new Intent(getContext(), AnimePlayActivity.class);
                intent.putExtra("pic", item.getPic());
                intent.putExtra("yhid", item.getId());
                intent.putExtra("type", 2);
                intent.putExtra("titleName", item.getName());
                startActivity(intent);

            }
        });

    }


    @Override
    public void networkMessage() {
        getTypeSearch();

    }


    public void getTypeSearch() {
//        yhList.clear();
//        lryList.clear();
        // 视频 1是YH  2是LRY  漫画 1是快看 2是LRY

        int anInt = SPStaticUtils.getInt(AppConstants.SWITCHKEY, 1);
        if (anInt == 1) {
            if (yhList.size() == 0) {
                getYHSearch(typeName);
                LogUtils.d("我做了网络请求B");

            } else {
                animeYHAdapter.replaceData(yhList);
            }
            binding.rvYh.setVisibility(View.VISIBLE);
            binding.rvLry.setVisibility(View.GONE);

            binding.swipeYh.setVisibility(View.VISIBLE);
            binding.swipeLry.setVisibility(View.GONE);


        } else if (anInt == 2) {
            getLRYSearch();
            binding.rvYh.setVisibility(View.GONE);
            binding.rvLry.setVisibility(View.VISIBLE);
            binding.swipeYh.setVisibility(View.GONE);
            binding.swipeLry.setVisibility(View.VISIBLE);


        }


    }

    private void getLRYSearch() {
        //取消请求
        if (callLRY != null) {
         callLRY.cancel();
        }
        if (isStateEnable()) {
            qLoading = new QLoading();
            qLoading.showNow(getChildFragmentManager(), "");
        }
        callLRY = Api.getInstance().service.getLRYSearch("videoType", typeName, pageLRY, pageSize);

//        Call<LRYSearchModel> call = Api.getInstance().service.getParam("title", "史莱姆", pageNo, pageSize);
        callLRY.enqueue(new Callback<AnimeLRYSearchModel>() {
            @Override
            public void onResponse(Call<AnimeLRYSearchModel> call, Response<AnimeLRYSearchModel> response) {
                LogUtils.d("网络请求数据" + call.toString(), response.body());

                if (response.body() != null && response.body().getData() != null) {
                    List<AnimeLRYSearchModel.DataBean> data = response.body().getData();

                    animeLrytAdapter.replaceData(response.body().getData());
                    if (pageLRY == 1) {
                        animeLrytAdapter.replaceData(response.body().getData());
                    } else {
                        if (response.body().getData().size() == 0) {
                            binding.swipeLry.finishLoadMoreWithNoMoreData();
                        } else {
                        }
                    }
                    for (int i = 0; i < data.size(); i++) {
                        lryList.add(data.get(i));
                    }
                    ;
                    animeLrytAdapter.replaceData(lryList);

                } else {
                    if (response.body() != null && response.body().getMsg() != null) {
                        ToastUtils.showLong(response.body().getMsg() + "状态码:" + response.code());
                    }
                }

                if (qLoading != null) {
                    qLoading.dismiss();
                }

            }

            @Override
            public void onFailure(Call<AnimeLRYSearchModel> call, Throwable t) {
                if (qLoading != null) {
                    qLoading.dismiss();
                }

                LogUtils.d("网络请求失败:" + t.getMessage());
                ToastUtils.showLong("网络请求失败:" + t.getMessage());

            }
        });
    }

    private void getYHSearch(String search) {

        if (animeTypeAdapter != null && animeTypeAdapter.getData() != null && animeTypeAdapter.getData().get(0) != null) {

            if (!typeName.equals(animeTypeAdapter.getData().get(0))) {
                typeName = animeTypeAdapter.getData().get(0);
            }
        }

        if (callYH != null) {
            callYH.cancel();
        }

        if (isStateEnable()) {
            qLoading = new QLoading();
            qLoading.showNow(getChildFragmentManager(), "");
        }


        map.clear();
        map.put("page", pageYH);
        map.put("keywords", search);
        callYH = Api.getInstance().service.getYHSearch(map);
        callYH.enqueue(new Callback<AnimeYHSearchModel>() {
            @Override
            public void onResponse(Call<AnimeYHSearchModel> call, Response<AnimeYHSearchModel> response) {
                LogUtils.d("getYHSearch网络请求数据" + call, response.body() + "--->" + networkIndex);

                if (response.body() != null && response.body().getData() != null && response.body().getData().getList() != null) {
                    networkIndex = 0;

                    List<AnimeYHSearchModel.DataBean.ListBean> data = response.body().getData().getList();
                    if (response.body().getData().getList().size() == 0) {
                        ToastUtils.showLong("暂无数据，或搜索名字不正确,或切换搜索模式试下");
                    }
                    total = response.body().getData().getTotal();
//                    dialog.dismiss();
                    animeYHAdapter.replaceData(response.body().getData().getList());


                    if (pageYH == 1) {
                        binding.rvYh.scrollToPosition(0);
                        animeYHAdapter.replaceData(response.body().getData().getList());
                    } else {
                        if (response.body().getData().getList().size() == 0) {
                            binding.swipeYh.finishLoadMoreWithNoMoreData();
                        } else {
                            binding.swipeYh.finishLoadMore();
                        }
                    }
                    for (int i = 0; i < data.size(); i++) {
                        yhList.add(data.get(i));
                    }

                    animeYHAdapter.replaceData(yhList);


                } else {
                    ToastUtils.showLong("没有数据，请切换服务器");
                    if (networkIndex <= 5) {
                        setTime(search);
                        networkIndex++;
                    } else {
                        ToastUtils.showLong("没有数据，请切换服务器");
                    }

                }


                if (qLoading != null) {
                    qLoading.dismiss();
                }
            }

            @Override
            public void onFailure(Call<AnimeYHSearchModel> call, Throwable t) {

                LogUtils.d("网络请求失败:" + t.getMessage());

                if (networkIndex <= 3) {
                    setTime(search);
                    networkIndex++;
                } else {
                    LogUtils.d("请切换模式试下  网络请求失败:" + t.getMessage());
                    ToastUtils.showLong("请切换模式  网络请求失败:" + t.getMessage());
                }

                if (qLoading != null) {
                    qLoading.dismiss();
                }

            }
        });
    }

    public void setTime(String search) {
        stopDisposable(disposable);
        disposable = Flowable.timer(5 * 1000, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        if(!isDestroy){
                            LogUtils.d("我做了网络请求C");
                            getYHSearch(search);
                        }


                    }
                });
    }


    /**
     * 关闭定时器
     *
     * @param disposable 定时器
     */
    private void stopDisposable(Disposable disposable) {
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        pageYH = 1;
        pageLRY = 1;


        if (animeTypeAdapter != null && animeTypeAdapter.getData() != null && animeTypeAdapter.getData().get(0) != null) {
            typeName = animeTypeAdapter.getData().get(0);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (callLRY != null) {
            callLRY.cancel();
        }
        isDestroy =true ;
        stopDisposable(disposable);
    }
}
